<template>
   <div class="m-right">
      <div class="publish" v-loading="loading">
         <div class="posts-type">
            <div>
               <ClientOnly>
                  <el-select v-model="postsData.postsSystemClassifyId" placeholder="可选分类" style="width: 130px;">
                     <el-option v-for="(item, index) in SystemData.SystemClassifyList" :key="index"
                        :label="item.classify_name" :value="item._id" />
                  </el-select>
               </ClientOnly>
            </div>
            <div style="display: flex;align-items: center;">
               <div class="type" :class="{ typeActive: postsData.postsType === 0 }" @click="postsData.postsType = 0">
                  默认
               </div>
               <div class="type" :class="{ typeActive: postsData.postsType === 1 }" @click="postsData.postsType = 1">
                  提问
               </div>
               <div class="type" :class="{ typeActive: postsData.postsType === 2 }" @click="postsData.postsType = 2">
                  投票
               </div>
            </div>
         </div>
         <div class="posts-content">
            <div v-if="postsData.postsType === 0">
               <input type="text" :placeholder="postsData.postsPermissionType === 0 ? '标题 （选填）' : '标题 （必填）'"
                  :style="{ backgroundColor: postsData.postsPermissionType === 0 ? '#FFF00000' : '#fff8ee' }"
                  v-model="postsData.postsTitle">
               <textarea minlength="5" v-model="postsData.postsContent" placeholder="来说点什么吧..."
                  style="overflow: hidden; overflow-wrap: break-word; height: 150px;"></textarea>
            </div>
            <div v-else class="weikaifang" style="">
               暂未开放
            </div>
         </div>
         <div class="posts-file">
            <div class="image-Array" v-if="state.imagePreviewList.length > 0">
               <div class="image" v-for="(item, index) in state.imagePreviewList" :key="index"
                  @click="delPreviewImage(item)">
                  <img :src="item.url" alt="" loading="lazy">
                  <div v-if="item.msg" class="mask"><span>{{ item.msg }}</span></div>
               </div>
               <div class="image" v-if="state.imagePreviewList.length > 0">
                  <div class="delimg" @click="delAbnormalImg">
                     <span class="iconfont icon-shanchu"></span>
                     <span class="text">删除异常项</span>
                  </div>
               </div>
            </div>
         </div>
         <div class="posts-file-btn">
            <div class="image">
               <iframe id="iframe_display" name="iframe_display" style="display: none;"></iframe>
               <form action="#" method="post" enctype="multipart/form-data" :onsubmit="uploadImg" target="iframe_display">
                  <input id="file" type="file" ref="file" multiple name="file" @change="uploadPictures">
               </form>
               <span class="iconfont icon-tupianxian"></span>
               <span class="text">图片</span>
            </div>
            <!-- <div class="link">
               <span class="iconfont icon-chaolianjie"></span>
               <span class="text">链接</span>
            </div> -->
            <div class="btn-publish">
               <ClientOnly>
                  <!-- <el-tooltip class="box-item" effect="light" content="是否额外开启黑名单/指定用户查看" placement="top">
                     <el-switch v-model="postsData.isCheck" />
                  </el-tooltip> -->
                  <div class="auth">
                     <el-select v-model="postsData.postsPermissionType" placeholder="Select" style="width: 130px;">
                        <el-option v-for="item in permissionOptions" :key="item.value" :label="item.label"
                           :value="item.value" :disabled="item.disabled" />
                     </el-select>
                  </div>
                  <div class="submit" @click="submit">立即发布</div>
               </ClientOnly>
            </div>
         </div>
         <div class="auth-tips">
            <div class="tips" v-if="postsData.postsPermissionType === 0">公开状态，所有人包括游客都可查看帖子所有内容（不开启左边开关时生效）</div>
            <!-- <div class="tips" v-if="postsData.permission === '1'">登录用户才能查看帖子内容/资源</div>
            <div class="tips" v-if="postsData.permission === '2'">用户评论帖子之后才能查看帖子内容/资源</div>
            <div class="tips" v-if="postsData.permission === '3'">
               用户支付费用之后才能查看帖子内容/资源
               <div>
                  <input type="text" placeholder="金额">
               </div>
            </div> -->
         </div>
         <div class="blacklist" v-if="postsData.isCheck">
            <p>
               <el-radio-group v-model="postsData.isCheck_options" class="ml-4">
                  <el-radio label="1" size="small">黑名单：不允许谁查看此贴 （是不会刷新在列表中）</el-radio>
                  <el-radio label="2" size="small">指定用户查看：登录后才能看到帖子</el-radio>
               </el-radio-group>
            </p>
            <div class="blacklist-content">
               开发中~
            </div>
            <div class="select">
               <div class="select-btn">选择倒霉蛋/幸运星</div>
            </div>
         </div>

         <!-- 未登录 -->
         <div class="noLogin" v-if="!userinfo._id">
            <span class="iconfont icon-show_yinsizhengce_fill"></span>
            <div class="title">您还未登录</div>
            <p>登陆后可展示更多内容</p>
            <div class="btn">
               <div @click="openLogin = true">登录</div>
            </div>
         </div>
      </div>
   </div>
</template>
<script lang="ts" setup >
import { storeToRefs } from 'pinia';
import { ElMessage } from "element-plus";
import { InfoFilled } from '@element-plus/icons-vue'
const { cnyzs, openLogin } = storeToRefs(cnyzsCommonpinia())
const { userinfo } = storeToRefs(cnyzsUserpinia())
const props = defineProps({
   SystemData: {
      type: Object,
      default: {
         SystemInfo: {},
         SystemConfig: {},
         SystemAnnounceList: {},
         SystemUserInfo: [],
         SystemUserList: [],
         SystemClassifyList: [],
         SystemPostsList: [],
      }
   }
});

const state: any = reactive({
   filelist: [], // file 
   imagePreviewList: [], // 客户端图片预览 blob:URL 列表
})
const loading = ref(false)

// 准备帖子数据 
const postsData: any = ref({
   // 所属系统ID
   postsSystemId: props.SystemData.SystemInfo._id,
   // 所属系统分类ID
   postsSystemClassifyId: '' || props.SystemData.SystemClassifyList[0]?._id || '',
   // 帖子权限类型
   postsPermissionType: 0,
   // 帖子类型？ 默认0 提问1 投票2
   postsType: 0,
   // 帖子标题
   postsTitle: '',
   // 帖子内容
   postsContent: '',
   // 隐藏内容
   postsHiddenContent: '',
   // 标签关联
   postsTags: '',
   // 帖子封面
   postsCovers: '',
   // 帖子图片
   postsImages: [],
})
// 权限选项
const permissionOptions = [
   {
      value: 0,
      label: '所有人可查看',
      disabled: false,
   },
]


/**
 * 压缩图片
 * @param file 
 */
function compressImg(file: File) {
   // 仅做图片压缩处理，msg 可能的值为：图片过大、校验中
   return new Promise((resolve, reject) => {
      const canvas = document.createElement('canvas');
      const ctx: any = canvas.getContext('2d');
      const img: any = new Image();
      const reader = new FileReader();

      let detect: object | null = null
      const fileName = file.name
      const random = Math.random()

      state.imagePreviewList.push({
         name: fileName,
         isLoaded: false,
         url: 'https://cos.alanoneup.com/Aoir/54/image/2023/05/27/1685174080367-29.gif?imageMogr2/thumbnail/500x',
         msg: '校验中...',
         random
      })

      reader.readAsDataURL(file);
      // loadImg
      reader.addEventListener("load", () => {
         const curItem: any = state.imagePreviewList.find((item: any) => item.random === random)

         // 如果正常 不显示任何内容
         curItem.msg = ''

         // 判断文件类型
         if (!/^image\//i.test(file.type)) {
            curItem.msg = '格式错误'
            detect = {
               code: 500,
               fileName,
               msg: '不支持该类型',
               type: 'error',
            }
         }

         if (/^image\/gif$/g.test(file.type)) {
            curItem.url = URL.createObjectURL(file)
            curItem.isLoaded = true
            detect = {
               code: 200,
               fileName,
               msg: '',
               url: curItem.url,
               file,
            }
         }

         // let max = 15120 * 1024
         let max = 5120 * 1024
         if (file.size > max) {
            curItem.msg = '超5M限制'
            detect = {
               code: 500,
               fileName,
               msg: '不能超过 5MB',
               type: 'warning',
            }
         }


         const isRepeat = state.imagePreviewList.filter((item: any) => item.name === fileName)
         if (isRepeat.length >= 2) {
            curItem.msg = '重复图片'
            detect = {
               code: 500,
               fileName,
               msg: '重复图片',
               type: 'warning',
            }
         }

         img.src = reader.result; // base64
         img.addEventListener('load', (e: Event) => {

            canvas.width = 150; // 缩略图宽度为 150px
            canvas.height = canvas.width * (img.height / img.width);
            ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);

            // 将 canvas 转为 blob 类型
            canvas.toBlob((blob: any) => {
               if (!curItem.isLoaded) {
                  curItem.url = URL.createObjectURL(blob)
               }
               if (!detect) {
                  detect = {
                     code: 200,
                     fileName,
                     url: curItem.url,
                     file,
                  }
               }
               resolve(detect)
            }, 'image/webp', 0.5);
         })

         img.addEventListener('error', (e: Event) => {
            curItem.msg = '错误格式'
            resolve({
               code: 500,
               fileName,
               msg: '不支持文件类型',
               type: 'error'
            })
         })
      });

      reader.addEventListener('error', () => {
         resolve({
            code: 500,
            fileName,
            msg: '文件加载失败',
            type: 'error'
         })
      })
   })
}
// 选择图片 且进行压缩处理
let imgs: any = []
const uploadPictures = async (e: any) => {
   try {
      const fileArray: any = Array.from(e.target.files)
      const promiseList = fileArray.map((file: File) => compressImg(file))
      const resultList = await Promise.all(promiseList)
      const errs = resultList.filter(result => result.code !== 200)
      imgs.push(...resultList.filter(result => result.code === 200))
      errs.forEach(({ msg: message, type }) => ElMessage({ type, message }))
   }
   catch (error) {
      console.error('导入图片错误:', error)
   }
}
// 删除某张预览图
const delPreviewImage = (item: any) => {
   state.imagePreviewList.forEach((v: any, index: number) => {
      if (item.random === v.random) state.imagePreviewList.splice(index, 1)
   });
}
// 删除所有异常图片
const delAbnormalImg = () => {
   state.imagePreviewList = state.imagePreviewList.filter((v: any, index: number) => v.msg === '');
}
// 上传漫画封面图片 返回图片地址
const uploadImg = (event?: any) => {
   // event.preventDefault()
   // const img: any = await commonUpload(this.fileList)
   // this.fileList = []
   // return img.data
}


/**
 *  发布帖子 (默认社区类型帖子)
 */
// 自动选择第一个分类

const submit = async () => {
   if (!postsData.value.postsSystemId) return ElMessage.warning('参数错误，请刷新页面')
   // 判断是否登录
   if (!userinfo.value._id) return openLogin.value = true
   // 判断是否有权限发帖子
   // 是否已经加入当前社区
   if (!props.SystemData.SystemUserInfo.systemUserJoin) return ElMessage.warning('您未加入该社区')
   // 校验一些必须参数
   if (!postsData.value.postsContent) return ElMessage.warning('内容不能为空')
   if (!postsData.value.postsSystemClassifyId) return ElMessage.warning('请选择分类')
   // 是否黑名单用户
   // ...

   // 判断类型 (默认类型，提问类型，投票类型)
   // 默认类型
   if (postsData.value.postsType === 0) {

      // 上传图片
      loading.value = true
      async function uploadImg() {
         // 判断有没有需要上传的图片
         if (imgs.length > 0) {
            ElMessage.success('正在上传图片...')
            // 判断是什么储存方式，使用对应的请求
            switch (cnyzs.value.COMMON_SPBM.SPBM) {
               case 'local':
                  console.log("本地存储");
                  return []
               case 'cos':
                  const cos = new Cos()
                  const promiseList = await imgs.map(async (file: any) => {
                     const obj = { File: file.file }
                     return await cos.putObject(obj, true, (progressData: any) => {
                        console.log('进度：' + progressData.percent + '%; 速度：' + progressData.speed + 'Mb/s;');
                        console.log('编号：', progressData.taskId);
                     })
                  })
                  return await Promise.all(promiseList)
               case 'oss':
                  console.log("阿里云OSS");

                  return []
               case 'kodo':
                  console.log("七牛云KODO");

                  return []
               case 'uss':
                  console.log("又拍云USS");

                  return []
               default:
                  return []
            }
         }
         else {
            return []
         }
      }
      const imagelist = await uploadImg()
      postsData.value.postsImages = imagelist.map((i: any) => {
         return i.UploadResult.ProcessResults.Object.Key
      })
      // 发布帖子
      const path = '/api/cnyzs-system-posts/ForumPublish'
      const res: any = await cnyzsRequest(path, { method: 'POST', data: postsData.value })
      if (res.status === 200) {
         ElMessage.success(res.message)
         loading.value = false
         setTimeout(() => {
            window.location.reload()
         }, 2000)
      }
      return
   }
   // 提问类型
   if (postsData.value.postsType === 1) {
      ElMessage.error('暂时无法发布提问贴')
      return
   }
   // 投票类型
   if (postsData.value.postsType === 2) {
      ElMessage.error('暂时无法发布投票贴')
      return
   }
}



</script>
<style lang="scss" scoped>
.m-right {
   width: 100%;
   margin-left: 16px;
   margin-bottom: 20px;

   .publish {
      width: 100%;
      padding: 15px;
      background-color: #FFF;
      border-radius: var(--aoir-border-radius);
      box-shadow: var(--aoir-box-shadow);
      position: relative;

      .noLogin {
         position: absolute;
         left: 0;
         top: 0;
         width: 100%;
         height: 100%;
         display: flex;
         flex-direction: column;
         justify-content: center;
         align-items: center;
         z-index: 5;
         background-color: #ffffff85;
         border-radius: var(--aoir-border-radius);

         .iconfont {
            font-size: 38px;
            font-weight: 600;
            color: #4caf80;
            margin-bottom: 15px;
         }

         .title {
            font-size: 22px;
            margin-bottom: 10px;
         }

         p {
            font-size: 14px;
            margin-bottom: 15px;
            color: #AAA;
         }

         .btn {
            display: flex;

            div {
               padding: 6px 25px;
               border-radius: 7px;
               background-color: var(--aoir-color-primary);
               color: #FFF;
               font-size: 15px;
               cursor: pointer;
               transition: all .2s;

               &:hover {
                  transform: translateY(-2px);
               }

               &:active {
                  transform: translateY(2px);
               }

               &:nth-child(1) {
                  // margin-right: 15px;
                  // background-color: var(--aoir-color-primary);
                  background-color: #baa565;
               }
            }
         }
      }

      .posts-type {
         display: flex;
         align-items: center;
         justify-content: space-between;
         margin-bottom: 10px;

         .type {
            cursor: pointer;
            color: #a3a3a3;
            transition: all 0.2s;
            font-size: 13px;
            padding: 4px 8px;
            margin-left: 20px;
            background: #f5f5f5;
            border-radius: 5px;
            font-weight: 600;

            &:active {
               transform: translateY(2px);
            }

            &:hover {
               background: #F5F5F5;
               color: var(--aoir-color-primary);
            }
         }

         .typeActive {
            background: #F5F5F5;
            color: var(--aoir-color-primary);
         }
      }

      .posts-content {
         min-height: 215.3333px;
         border: 1px solid #f5f6f7;
         border-radius: var(--aoir-border-radius) var(--aoir-border-radius);
         padding: 5px;


         input {
            width: 100%;
            height: 45px;
            border: 0;
            font-size: 16px;
            background-color: #FFF;
            border-bottom: 1px solid #f5f6f7;
            margin-bottom: 5px;
            border-radius: 4px;
            caret-color: var(--aoir-color-primary-2);
            padding: 0 10px;

            &::placeholder {
               color: #CCD0DB;
            }
         }

         textarea {
            border: 0;
            width: 100%;
            resize: none;
            font-size: 16px;
            line-height: 26px;
            caret-color: var(--aoir-color-primary-2);
            padding: 5px 10px;
            white-space: pre-wrap;

            &::placeholder {
               color: #CCD0DB;
               font-size: 16px;
            }
         }

         .weikaifang {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 15px;
            border: 1.5px solid rgba(0, 0, 0, 0.14);
            border-radius: var(--aoir-border-radius);
            color: #8b8b8b;
            flex-direction: column;
            background-color: #FFF;
            cursor: pointer;
            box-shadow: 0px 0px 35px 0px rgba(181, 181, 181, 0.45);
            padding: 20px;
         }
      }

      .posts-file {
         .image-Array {
            margin-top: 10px;
            width: 100%;
            padding: 10px 10px 0;
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            border: 1px dashed #dfdfdf;
            border-radius: 5px;

            .image {
               width: 83.7px;
               height: 83.7px;
               margin-right: 10px;
               margin-bottom: 10px;
               cursor: pointer;
               box-shadow: 0 0 8px 0 rgba(70, 70, 70, 0.26);
               border-radius: 4px;
               // overflow: hidden;
               position: relative;
               border-radius: var(--aoir-border-radius);

               img {
                  position: absolute;
                  left: 0;
                  top: 0;
                  max-width: 100%;
                  height: auto;
                  object-fit: cover;
                  border: 0;
                  vertical-align: text-top;
                  width: 100%;
                  height: 100%;
                  box-shadow: inset 0 0 1px #898989;
                  border-radius: 4px;
                  border-radius: var(--aoir-border-radius);
               }

               .mask {
                  position: absolute;
                  left: 0;
                  top: 0;
                  z-index: 1;
                  width: 100%;
                  height: 100%;
                  display: flex;
                  justify-content: center;
                  align-items: center;

                  span {
                     padding: 4px 8px;
                     background-color: rgb(0 0 0 / 78%);
                     color: #FFF;
                     border-radius: 3px;
                     font-size: 13px;
                  }
               }

               &:nth-child(6n) {
                  margin-right: 0px;
               }

               &:nth-last-child(1) {
                  box-shadow: 0 0 8px 0 rgba(70, 70, 70, 0);
               }

               .delimg {
                  width: 100%;
                  height: 100%;
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  align-items: center;

                  border: 1px solid rgba(0, 0, 0, 0.14);
                  border-radius: var(--aoir-border-radius);
                  color: #8b8b8b;
                  cursor: pointer;

                  &:hover {
                     box-shadow: 0px 0px 35px 0px rgba(181, 181, 181, 0.45);
                  }

                  .iconfont {
                     font-size: 25px;
                     font-weight: 600;
                     color: red;
                     margin-bottom: 5px;
                  }

                  .text {
                     font-size: 13px;
                  }

               }
            }
         }
      }

      .posts-file-btn {
         padding: 10px 5px;
         display: flex;
         align-items: center;

         .text {
            font-size: 15px;
            color: #666666;
         }

         .image {
            margin-right: 22px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;

            #file {
               position: absolute;
               left: 50%;
               top: 50%;
               z-index: 1;
               transform: translate(-50%, -50%);
               width: 100%;
               height: 100%;
               opacity: 0;
               cursor: pointer;
            }

            .iconfont {
               margin-right: 3px;
               font-size: 27px;
               transform: translateY(1px);
               color: #ff9800;
               text-shadow: 0 0 1px #ff9800;
            }

            &:hover {
               opacity: .8;
            }
         }

         .link {
            display: flex;
            align-items: center;
            cursor: pointer;

            .iconfont {
               margin-right: 7px;
               font-size: 16px;
               transform: translateY(1px);
               color: #03a9f4;
               text-shadow: 0 0 1px #03a9f4;
            }

            &:hover {
               opacity: .8;
            }
         }

         .btn-publish {
            flex: 1;
            margin-left: 30px;
            display: flex;
            justify-content: flex-end;

            .auth {
               margin: 0 15px;
            }

            .submit {
               padding: 7px 14px;
               background-color: var(--aoir-color-primary);
               color: #FFF;
               font-size: 14px;
               font-weight: 600;
               border-radius: 5px;
               cursor: pointer;

               &:hover {
                  opacity: .8;
               }

               &:active {
                  transform: translateY(1.5px);
               }
            }
         }
      }

      .auth-tips {
         width: 100%;
         height: auto;

         .tips {
            display: block;
            width: 100%;
            background-color: #fff8ee;
            padding: 8px 10px;
            border-radius: 4px;
            font-size: 13px;
            color: #9d9d9d;

            input {
               margin-top: 10px;
               width: 100%;
               border-color: #f5f6f7;
               background: #fff;
               padding: 7px;
               margin-bottom: 10px;
               border: 1px solid #ccc;
               border: 0;

               &::placeholder {
                  font-size: 15px;
                  color: #CCD0DB;
               }
            }
         }
      }

      .blacklist {
         width: 100%;
         background-color: #f2f2f2;
         border-radius: 4px;
         padding: 8px 10px;
         font-size: 13px;
         color: #9d9d9d;
         margin-top: 10px;

         p {
            margin: 0 0 8px 0;
         }

         .blacklist-content {
            width: 100%;
            height: 35px;
            background-color: #FFF;
            padding: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
         }

         .select {
            margin-top: 8px;
            width: 100%;


            &-btn {
               width: 150px;
               padding: 7px 14px;
               background-color: var(--aoir-color-primary);
               color: #FFF;
               font-size: 14px;
               font-weight: 600;
               border-radius: 5px;
               cursor: pointer;
               display: flex;
               justify-content: center;

               &:hover {
                  opacity: .8;
               }

               &:active {
                  transform: translateY(2px);
               }
            }
         }
      }
   }
}
</style>